
<template>
	<view>
		<cu-custom :bgColor="showBg ? 'bg-themeColor': 'text-white'" :isBack="true">
			<block slot="backText">返回</block>
			<block slot="content">拼团成功</block>
		</cu-custom>
    <view class="linearBack"></view>
    <view style="margin-top:-150rpx">
      <view class="cu-card article">
        <view class="cu-item">
          <view class="content">
            <image :src="grouponInfo.picUrl" mode="aspectFill" class="row-img margin-top-xs"></image>
            <view class=" row-info block">
              <view class="text-black margin-top-sm overflow-2  text-bold">{{grouponInfo.goodsSpu.name}}</view>
              <view class="flex">
                <view class="text-black margin-top-xs overflow-2 text-gray text-sm">
                  <text>{{ grouponInfo.grouponNum }}人团</text>
                  <text class="margin-lr-xs">|</text> 已有{{
                    grouponInfo.launchNum
                  }}人参与
                </view>
              </view>
              <view class="text-gray text-sm overflow-1" v-if="grouponInfo.goodsSpu&&grouponInfo.goodsSku.specs&&grouponInfo.goodsSku.specs.length > 0">{{specInfo}}</view>
              <view class="flex justify-start margin-top-lg align-center">
                <view class="text-price text-bold text-xl text-red">{{grouponUser.grouponPrice}}</view>
                <view class="text-price text-decorat text-gray margin-left-sm">{{grouponInfo.goodsSku.salesPrice}}</view>
              </view>
            </view>
          </view>
        </view>
      </view>

      <view class="cu-list menu card-menu radius" v-if="grouponUserList.length > 0">
        <view class="bg-white text-center padding-tb text-bold text-spacing" v-if="grouponUser.status != 1"> <text class="themeColor">{{ grouponInfo.grouponNum }}</text> 人成团 还差<text class="themeColor">{{grouponInfo.grouponNum - grouponUserList.length}}</text>人</view>
        
        <view class="bg-white padding-tb-sm">
          <view  v-if="grouponUser.status == 1" class="grouponSuccess bg-white">
            <image class="" src='../../../static/images/grouponSuccess.png' />
            <view class="text-center themeColor text-lg margin-bottom-lg text-bold text-spacing">拼团成功</view>
          </view>
          <view class="content text-center">
            <view class="cu-avatar round lg margin-xs text-yellow groupon-user" :style="'background-image:url(' + grouponUser.headimgUrl + ');'">
              <view class="cu-tag badge bg-yellow">团长</view>
            </view>
            <view class="cu-avatar round lg margin-xs text-yellow groupon-user" v-for="(item, index) in grouponUserList" :key="index"
            v-if="item.id != grouponUser.id" :style="'background-image:url(' + item.headimgUrl + ');'"></view>
            <view class="cu-avatar round lg margin-xs groupon-user-no" v-for="(item, index) in grouponInfo.grouponNum - grouponUserList.length"
            :key="index">
              <text>?</text>
            </view>
          </view>
        </view>
        <view class="bg-white padding-lr text-center padding-tb">
          <!-- 没参与 -->
          <view v-if="!grouponUser.grouponUser">
            <button class="button1" v-if="grouponInfo.enable == '1' && grouponUser.status == '0'"
              @tap="toGroupon">参与拼团</text></button>
            <button class="button2" v-if="grouponUser.status == '2'">活动已过期</button>
          </view>
          <!-- 已经参与 -->
          <view v-if="grouponUser.grouponUser">
            <button class="button1" v-if="grouponUser.status == '0'" @tap="shareShowFun">邀请好友拼团</button>
            <button class="button1" v-if="grouponUser.status == '1'" @tap="grouponAgain">再拼一团</button>
            <button class="button3" v-if="grouponUser.status == '2'">该拼团已过期</button>
          </view>
        </view> 
        <view class="bg-white justify-center padding-top-sm" v-if="grouponUser.status == '0'">
          <view class="text-center padding-tb">
            <view class="text-spacing text-gray text-bold text-sm margin-bottom-sm">距结束还剩</view>
            <count-down class="text-red" :bgType="false" :outTime="dateUtil.getOutTime(grouponUser.validEndTime)" @countDownDone="countDownDone" />
          </view>
        </view>
      </view>
      <view class="cu-card">
        <view class="cu-item">
          <view class="bg-white solid-bottom padding-tb flex justify-center">
            <image src="../../../static/images/bargainRankLeft.png" style="width: 66rpx; height: 18rpx; margin: auto 0" />
            <view class="text-center text-lg text-bold themeColor margin-lr-sm">
            拼团攻略</view>
            <image src="../../../static/images/bargainRankRight.png"
              style="width: 66rpx; height: 18rpx; margin: auto 0" />
          </view>
          <view class="flex">
            <view class="flex-sub text-center padding-tb-sm">
              <view class="round glTag text-white margin-tb-sm">1</view>
              <view class="text-sm text-gray margin-tb-xs">选择商品付款</view>
              <view class="text-xs text-gray">开团参团</view>
            </view>
            <view class="flex-sub text-center padding-tb-sm">
              <view class="round glTag text-white margin-tb-sm">2</view>
              <view class="text-sm text-gray margin-tb-xs">好友支付参团</view>
              <view class="text-xs text-gray">邀请并等待</view>
            </view>
            <view class="flex-sub text-center padding-tb-sm">
              <view class="round glTag text-white margin-tb-sm">3</view>
              <view class="text-sm text-gray margin-tb-xs">顺利开团</view>
              <view class="text-xs text-gray">达到拼团人数</view>
            </view>
            <view class="flex-sub text-center padding-tb-sm">
              <view class="round glTag text-white margin-tb-sm">4</view>
              <view class="text-sm text-gray margin-tb-xs">等待发货</view>
              <view class="text-xs text-gray">组团成功</view>
            </view>
          </view>
        </view>
      </view>
      <view class="cu-card mar-top-30">
        <view class="cu-item">
          <view class="bg-white solid-bottom padding-tb flex justify-center">
            <image src="../../../static/images/bargainRankLeft.png" style="width: 66rpx; height: 18rpx; margin: auto 0" />
            <view class="text-center text-lg text-bold themeColor margin-lr-sm">
            拼团规则</view>
            <image src="../../../static/images/bargainRankRight.png"
              style="width: 66rpx; height: 18rpx; margin: auto 0" />
          </view>
          <view class="padding">{{ grouponInfo.grouponRule }}</view>
        </view>
      </view>
    </view>
      
		<!-- html转wxml -->


		<poster id="poster" ref='posterRef' :hide-loading="false" :preload="false" :config="posterConfig" @success="onPosterSuccess"
		 @fail="onPosterFail"></poster>
		<view :class="'cu-modal bottom-modal ' + shareShow">
			<view class="cu-dialog">
				<view class="cu-bar bg-white">
					<view class="action text-green"></view>
					<view class="action text-red" @tap="shareHide">取消</view>
				</view>
				<view class="padding flex flex-direction">
					<share-friends
						:shareObj="{
								title: grouponInfo.shareTitle,
								desc: grouponInfo.goodsSpu.name,
								imgUrl: grouponInfo.picUrl,
						}"></share-friends>

					<button class="cu-btn margin-tb-sm lg round shadow-blur" :class="'bg-'+theme.themeColor" @tap="onCreatePoster">生成海报</button>
				</view>
			</view>
		</view>

		<view :class="'cu-modal ' + (posterShow ? 'show' : '')">
			<view class="cu-dialog">
				<view style="height: calc(100vh - 200rpx)">
					<image :src="posterUrl" style="height: 100%;"></image>
				</view>
				<view class="cu-bar bg-white">
					<view class="action margin-0 flex-sub" @tap="hidePosterShow">取消</view>

					<!-- #ifdef MP || APP-PLUS -->
					<view class="action margin-0 flex-sub solid-left text-red text-bold" @tap="savePoster">保存到相册</view>
					<!-- #endif -->
					<!-- #ifdef H5 -->
					<view class="action margin-0 flex-sub solid-left text-red text-bold"  @tap="hidePosterShow">长按图片可保存或分享</view>
					<!-- #endif -->
				</view>
			</view>
		</view>

		<!-- #ifdef H5 || APP-PLUS -->
		<!-- 二维码组件，不显示，只用来生成二维码调用 说明文档 https://github.com/q310550690/uni-app-qrcode -->
		<!-- 该组件生成二维码时需要canvas元素装载,固直接引用组件没有使用js，效果一样 -->
		<view>
			<tki-qrcode ref="qrCodeRef" :size="200" :show="false" :val="curLocalUrl" @result="startCreatePoster"  icon="/static/public/logo.png"></tki-qrcode>
		</view>
		<!-- #endif -->
	</view>
</template>

<script>
import shopInfo from "@/components/shop-info/index";
import util from "@/utils/util";
const { base64src } = require("@/utils/base64src.js");
const app = getApp();
import api from "@/utils/api";
import dateUtil from "@/utils/dateUtil.js";
import jweixin from "@/utils/jweixin";

import poster from "@/components/wxa-plugin-canvas/poster/index";
import countDown from "../../../component/count-down/index";
import tkiQrcode from "@/components/tki-qrcode/tki-qrcode.vue";
import shareFriends from "@/components/share-friends/index.vue";

export default {
  data() {
    return {
      showBg: false,
      CustomBar: this.CustomBar,
      theme: app.globalData.theme, //全局颜色变量
      dateUtil: dateUtil,
      page: {
        searchCount: false,
        current: 1,
        size: 100,
        ascs: "",
        //升序字段
        descs: "create_time",
      },
      parameter: {},
      grouponUser: {
        grouponNum: 0,
        validBeginTime: "",
        validEndTime: "",
      },
      grouponUserList: [],
      grouponInfo: {
        launchNum: 0,
        shopInfo: {},
        goodsSpu: {},
        goodsSku: {},
      },
      shareShow: "",
      curLocalUrl: "",
      userInfo: null,
      modalRule: "",
      id: "",
      specInfo: "",
      loadmore: false,
      posterUrl: "",
      posterShow: false,
      posterConfig: "",
      shopInfo: {},
    };
  },

  components: {
    poster,
    countDown,
    shareFriends,
    tkiQrcode,
  },
  props: {},

  onShow() {
    app.initPage().then((res) => {
      this.grouponUserList = [];
      this.grouponUserGet();
      this.grouponUserPage();
    });
  },
  onPageScroll(e) {
    if (e.scrollTop > 30) {
      this.showBg = true;
    } else {
      this.showBg = false;
    }
  },
  onLoad(options) {
    let id;

    if (options.referee) {
        let params = {
          referee: options.referee,
          wxUseropenId: uni.getStorageSync('user_info').wxUseropenId
        }
        this.bindSpread(params)
    }
    if (options.scene) {
      //接受二维码中参数
      id = decodeURIComponent(options.scene);
    } else {
      id = options.id;
    }
    if (options.shopId) {
      this.shopMethods(options.shopId);
    }
    this.id = id;
    this.userInfo = uni.getStorageSync("user_info");
  },

  onShareAppMessage: function () {
    let grouponInfo = this.grouponInfo;
    let title = grouponInfo.shareTitle;
    let imageUrl = grouponInfo.picUrl;
    let path = "";
    path =
      "pages_grid/pages/groupon/groupon-user-detail/index?id=" +
      this.grouponUser.id +
      "&referee=" +
      (uni.getStorageSync("user_info").refereeId || "") +
      "&shopId=" +
      this.shopInfo.id;
    return {
      title: title,
      path: path,
      imageUrl: imageUrl,
      success: function (res) {
        if (res.errMsg == "shareAppMessage:ok") {
          console.log(res.errMsg);
        }
      },
      fail: function (res) {
        // 转发失败
      },
    };
  },
  methods: {
			//推荐人绑定
			bindSpread(data) {
				console.log(`推荐人绑定参数`, data)
				api.bindSpread(data).then(res => {
					console.log(`推荐人绑定接口返回参数`, res)
				});
			},
    shopMethods(shopId) {
      api.shopInfoGet(shopId).then((res) => {
        this.shopInfo = res.data;
      });
    },
    //查询拼团记录信息
    grouponUserGet() {
      api.grouponUserGet(this.id).then((res) => {
        let grouponUser = res.data;
        let grouponInfo = grouponUser.grouponInfo;
        let goodsSku = grouponInfo.goodsSku;
        let specInfo = "";
        goodsSku.specs.forEach(function (specItem, index) {
          specInfo = specInfo + specItem.specValueName;
          if (goodsSku.specs.length != index + 1) {
            specInfo = specInfo + ";";
          }
        });
        this.grouponUser = grouponUser;
        // grouponInfo.shopInfo = grouponInfo.shopInfo ? grouponInfo.shopInfo : {}
        grouponInfo.goodsSpu = grouponInfo.goodsSpu ? grouponInfo.goodsSpu : {};
        grouponInfo.goodsSku = grouponInfo.goodsSku ? grouponInfo.goodsSku : {};
        this.grouponInfo = grouponInfo;
        this.specInfo = specInfo;
      });
    },
    grouponUserPage() {
      api
        .grouponUserPage(
          Object.assign(
            {
              groupId: this.id,
            },
            this.page,
            util.filterForm(this.parameter)
          )
        )
        .then((res) => {
          let grouponUserList = res.data.records;
          this.grouponUserList = [...this.grouponUserList, ...grouponUserList];
          if (grouponUserList.length < this.page.size) {
            this.loadmore = false;
          }
        });
    },

    //参与拼团
    toGroupon(e) {
      let grouponInfo = this.grouponInfo;
      let goodsSpu = grouponInfo.goodsSpu;
      let goodsSku = grouponInfo.goodsSku;

      if (goodsSku.stock > 0) {
        /* 把参数信息异步存储到缓存当中 */
        uni.setStorage({
          key: "param-orderConfirm",
          data: [
            {
              spuId: goodsSpu.id,
              skuId: goodsSku.id,
              quantity: 1,
              salesPrice: grouponInfo.grouponPrice,
              spuName: goodsSpu.name,
              specInfo: this.specInfo,
              picUrl: goodsSku.picUrl ? goodsSku.picUrl : goodsSpu.picUrls[0],
              freightTemplat: goodsSpu.freightTemplat,
              weight: goodsSku.weight,
              volume: goodsSku.volume,
              orderType: "2",
              marketId: grouponInfo.id,
              relationId: this.grouponUser.id,
              shopInfo: this.shopInfo,
            },
          ],
        });
        uni.navigateTo({
          url: "/pages/groupon/groupon-order-confirm/index",
        });
      } else {
        uni.showToast({
          title: "拼团商品库存不足",
          icon: "none",
          duration: 2000,
        });
      }
    },

    shareShowFun() {
      // #ifdef H5
      this.curLocalUrl = window.location.href;
      // #endif
      // #ifdef APP-PLUS
      this.curLocalUrl = util.setAppPlusShareUrl();
      // #endif
      this.shareShow = "show";
    },

    shareHide() {
      this.shareShow = "";
    },

    onPosterSuccess(e) {
      this.posterUrl = e;
      this.posterShow = true;
    },

    onPosterFail(err) {
      console.error(err);
    },
    grouponAgain(){
      uni.redirectTo({
        url:'/pages_grid/pages/groupon/groupon-list/index'
      })
    },
    hidePosterShow() {
      this.posterShow = false;
      this.shareShow = "";
    },
    /**
     * 异步生成海报
     */
    onCreatePoster() {
      // #ifdef MP
      api
        .qrCodeUnlimited({
          theme: app.globalData.theme, //全局颜色变量
          page: "pages_grid/pages/groupon/groupon-user-detail/index",
          scene: this.grouponUser.id,
        })
        .then((res) => {
          base64src(res.data, (res) => {
            this.startCreatePoster(res);
          });
        });
      // #endif
      // #ifdef H5 || APP-PLUS
      uni.showLoading({
        title: "生成中",
        mask: true,
      });
      this.$refs.qrCodeRef._makeCode(); // H5需要先生成二维码后 才能生成海报
      // #endif
    },

    startCreatePoster(res) {
      // 开始 生成海报
      let desc = "长按识别小程序码";
      let shareImg = this.grouponInfo.picUrl;
      // #ifdef H5 || APP-PLUS
      desc = "长按识别二维码";
      // h5的海报分享的图片有的有跨域问题，所以统一转成base64的
      // 之所以不在组件里面转换是因为无法区分哪张image图片需要处理，一般处理主图
      shareImg = util.imgUrlToBase64(shareImg);
      // #endif
      let qrCode = res; //海报配置请参考 https://github.com/jasondu/wxa-plugin-canvas
      let posterConfig = {
        width: 750,
        height: 1280,
        backgroundColor: "#fff",
        debug: false,
        blocks: [
          {
            width: 690,
            height: 808,
            x: 30,
            y: 183,
            borderWidth: 2,
            borderColor: "#f0c2a0",
            borderRadius: 20,
          },
          {
            width: 634,
            height: 74,
            x: 59,
            y: 770,
            backgroundColor: "#fff",
            opacity: 0.5,
            zIndex: 100,
          },
        ],
        texts: [
          {
            x: 30,
            y: 113,
            baseLine: "top",
            text: this.grouponInfo.shareTitle,
            fontSize: 38,
            color: "#080808",
          },
          {
            x: 92,
            y: 810,
            fontSize: 38,
            baseLine: "middle",
            text: this.grouponInfo.goodsSpu.name,
            width: 570,
            lineNum: 1,
            color: "#080808",
            zIndex: 200,
          },
          {
            x: 59,
            y: 895,
            baseLine: "middle",
            text: [
              {
                text: "拼团价",
                fontSize: 28,
                color: "#ec1731",
              },
              {
                text: "¥" + this.grouponInfo.grouponPrice,
                fontSize: 36,
                color: "#ec1731",
                marginLeft: 30,
              },
            ],
          },
          {
            x: 522,
            y: 895,
            baseLine: "middle",
            text: "原价 ¥" + this.grouponInfo.goodsSku.salesPrice,
            fontSize: 28,
            color: "#929292",
          },
          {
            x: 59,
            y: 945,
            baseLine: "middle",
            text: [
              {
                text: this.grouponInfo.goodsSpu.sellPoint,
                fontSize: 28,
                color: "#929292",
                width: 570,
                lineNum: 1,
              },
            ],
          },
          {
            x: 360,
            y: 1065,
            baseLine: "top",
            text: desc,
            fontSize: 38,
            color: "#080808",
          },
          {
            x: 360,
            y: 1123,
            baseLine: "top",
            text: "快来和我一起拼一单吧！",
            fontSize: 28,
            color: "#929292",
          },
        ],
        images: [
          {
            width: 634,
            height: 634,
            x: 59,
            y: 210,
            url: shareImg,
          },
          {
            width: 220,
            height: 220,
            x: 92,
            y: 1020,
            url: qrCode,
          },
        ],
      };
      let userInfo = uni.getStorageSync("user_info");

      if (userInfo && userInfo.headimgUrl) {
        //如果有头像则显示
        posterConfig.images.push({
          width: 62,
          height: 62,
          x: 30,
          y: 30,
          borderRadius: 62,
          url: userInfo.headimgUrl,
        });
        posterConfig.texts.push({
          x: 113,
          y: 61,
          baseLine: "middle",
          text: userInfo.nickName,
          fontSize: 32,
          color: "#8d8d8d",
        });
      }
      this.posterConfig = posterConfig;
      this.posterShow = true;
      this.$refs.posterRef.onCreate(false, this.posterConfig); // 入参：true为抹掉重新生成
    },
    //点击保存到相册
    savePoster: function () {
      var that = this;
      uni.saveImageToPhotosAlbum({
        filePath: that.posterUrl,
        success(res) {
          uni.showModal({
            content: "图片已保存到相册，赶紧晒一下吧~",
            showCancel: false,
            confirmText: "好的",
            confirmColor: "#333",
            success: function (res) {
              if (res.confirm) {
                /* 该隐藏的隐藏 */
                that.shareShow = "";
              }
            },
            fail: function (res) {
              console.log(res);
            },
          });
        },
      });
    },

    ruleShow() {
      this.modalRule = "show";
    },

    ruleHide() {
      this.modalRule = "";
    },

    countDownDone() {
      this.onLoad();
    },
  },
};
</script>
<style scoped>
.linearBack{
  width: 750rpx;
height: 280rpx;background: linear-gradient(180deg, #FFA56F 0%, #FF6A4B 39%, #F43E36 100%);

  margin-top: -120rpx;
}

</style>
<style>
.row-img {
    width: 230rpx !important;
    height: 230rpx !important;
  border-radius: 10rpx;
  margin-top:20rpx
}

.cu-bar.tabbar.shop .action {
  width: unset;
}

.cu-avatar {
  display: inline-flex !important;
}

.groupon-user {
  border-style: solid;
}

.groupon-user-no {
  border-style: dotted;
  background-color: #fff;
  color: #ccc;
}

.cu-btn {
  width: 100%;
  height: 76rpx;
}

.button1 {
  width: 636rpx;
  height: 70rpx;
  line-height: 70rpx;
  background: linear-gradient(180deg, #ffa56f 0%, #ff6a4b 39%, #f43e36 100%);
  border-radius: 28px;
  font-size: 28rpx;
  letter-spacing: 1px;
  color: #ffffff;
}
.button2 {
  width: 636rpx;
  height: 70rpx;
  line-height: 70rpx;
  font-size: 28rpx;
  border-radius: 28px;
  border: 1px solid #fea51a;
  background: #ffffff;
  color: #fea51a;
  letter-spacing: 1px;
}
.button3 {
  width: 636rpx;
  height: 70rpx;
  line-height: 70rpx;
  font-size: 28rpx;
  border-radius: 28px;
  color: #333333;
  overflow: hidden;
  letter-spacing: 1px;
}
button::after{
  border:none
}
.text-spacing {
  letter-spacing: 1px;
}
.themeColor {
  color: #e65c53;
}
.themeBgColor {
  background: #e65c53;
  color: #fff;
}
.bg-themeColor {
  background: linear-gradient(180deg, #ffa56f 0%, #ff6a4b 100%);
  color: #fff;
}
.glTag {
  width: 48rpx;
  height: 48rpx;
  line-height: 48rpx;
  text-align: center;
  background: linear-gradient(180deg, #ffa56f 0%, #ff6a4b 39%, #f43e36 100%);
  margin: 20rpx auto;
  font-size: 26rpx;
}
.grouponBack {
  width: 750rpx;
  height: 280rpx;
  background: linear-gradient(180deg, #ffa56f 0%, #ff6a4b 39%, #f43e36 100%);
  margin-top: -160rpx;
}
.grouponSuccess image{
  width: 268rpx;
  height: 94rpx;
  display: block;
  margin: 40rpx auto;
}
</style>
